package com.example.threadtest


import android.app.ProgressDialog
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.threadtest.databinding.ActivityMainBinding
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    private lateinit var binding: ActivityMainBinding
    private lateinit var progressDialog: ProgressDialog

    var updateIndex = 1
    var hander = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                updateIndex -> {
                    binding.textView.text = "Current Index: $updateIndex";updateIndex++
                }

                else -> {
                    binding.textView.text = "Unknown Message: ${msg.what}"
                }
            }

        }


    }
//    private lateinit var binder: MyForegroundService.DownloadBinder
//    private val serviceConnection = object : ServiceConnection {
//        private val TAG = "ServiceConnection"
//        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//
//            binder = service as MyForegroundService.DownloadBinder
//            binder.getStart()
//            binder.getProgress()
//        }
//
//        override fun onServiceDisconnected(name: ComponentName?) {
//
//            Log.d(TAG, "onServiceDisconnected: ")
//        }
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)

        setContentView(binding.root)
        // 初始化 ProgressDialog
        progressDialog = ProgressDialog(this)
        progressDialog.setMessage("Downloading...")
        progressDialog.setCancelable(false)

        // 可以在这里或某个事件监听器中启动 DownloadTask
        binding.changeTextBtn.setOnClickListener {
            val downloadTask = DownloadTask(this)
            downloadTask.execute()
        }
        binding.startService.setOnClickListener {
            val intent = Intent(this, MyForegroundService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
        }
        binding.stopService.setOnClickListener {
            val intent = Intent(this, MyForegroundService::class.java)

            stopService(intent)
        }
        binding.intentService.setOnClickListener {
            val intent = Intent(this, MyIntentService::class.java)
            startService(intent)
            Log.d(TAG, "onCreate:当前线程id:+${Thread.currentThread().id}")


        }
//        binding.bindService.setOnClickListener {
//            val intent = Intent(this, MyForegroundService::class.java)
//            bindService(intent, serviceConnection, BIND_AUTO_CREATE)
//        }
//        binding.unBindService.setOnClickListener {
//            unbindService(serviceConnection)
//        }


    }

    inner class DownloadTask(private val activity: MainActivity) : AsyncTask<Unit, Int, Boolean>() {


        override fun onPreExecute() {
            activity.progressDialog.show()
        }

        override fun doInBackground(vararg params: Unit?): Boolean = try {
            var downloadPercent = 0
            while (downloadPercent < 100) {
                // 模拟下载进度，这里假设每次增加1-10的随机值
                val progressIncrease = Random.nextInt(10) + 1
                Thread.sleep(100)
                downloadPercent += progressIncrease
                if (downloadPercent > 100) {
                    downloadPercent = 100 // 防止超过100
                }
                publishProgress(downloadPercent)
                // 模拟下载过程中的耗时操作
                Thread.sleep(100) // 休眠1000毫秒
            }
            true
        } catch (e: Exception) {
            false
        }

        override fun onProgressUpdate(vararg values: Int?) {
            // 在这里更新下载进度
            activity.progressDialog.setMessage("Downloaded ${values[0]?.toString() ?: "0"}%")
        }

        override fun onPostExecute(result: Boolean) {
            activity.progressDialog.dismiss() // 关闭进度对话框
            // 在这里提示下载结果
            if (result) {
                Toast.makeText(activity, "Download succeeded", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(activity, "Download failed", Toast.LENGTH_SHORT).show()
            }
        }
    }
}